// 修复JSON解析的请求工具
export default function request(url, options = {}) {
  // 从本地存储获取token
  let token = '';
  try {
    const userInfo = localStorage.getItem('user');
    if (userInfo) {
      const parsedInfo = JSON.parse(userInfo);
      token = parsedInfo.token || '';
    }
  } catch (err) {
    console.error('获取token失败:', err);
  }
  
  // 处理请求方法和请求头
  const method = options.method?.toUpperCase() || 'GET';
  const headers = {
    'Content-Type': 'application/json',
    ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
    ...options.headers
  };
  
  const requestOptions = {
    method,
    headers,
    ...options
  };
  
  // 处理请求体
  if (method !== 'GET' && options.body) {
    requestOptions.body = typeof options.body === 'string' 
      ? options.body 
      : JSON.stringify(options.body);
  }
  
  // 创建提示框元素的函数
  const showToast = (message) => {
    // 检查是否已有提示框，有则移除
    const existingToast = document.querySelector('.auth-toast');
    if (existingToast) {
      existingToast.remove();
    }
    
    // 创建提示框
    const toast = document.createElement('div');
    toast.className = 'auth-toast';
    toast.style.position = 'fixed';
    toast.style.top = '20px';
    toast.style.left = '50%';
    toast.style.transform = 'translateX(-50%)';
    toast.style.padding = '12px 20px';
    toast.style.backgroundColor = '#ff4d4f';
    toast.style.color = 'white';
    toast.style.borderRadius = '4px';
    toast.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    toast.style.zIndex = '9999';
    toast.style.transition = 'opacity 0.3s ease';
    toast.textContent = message;
    
    document.body.appendChild(toast);
    
    // 3秒后隐藏提示框
    setTimeout(() => {
      toast.style.opacity = '0';
      setTimeout(() => toast.remove(), 300);
    }, 3000);
  };
  
  // 返回Promise，确保正确解析JSON
  return new Promise((resolve, reject) => {
    fetch(url, requestOptions)
      .then(response => {
        if (!response.ok) {
          // 处理HTTP错误状态
          if (response.status === 401) {
            // 显示token无效提示
            showToast('登录已过期或token无效，请重新登录');
            // 清除本地存储的用户信息
            localStorage.removeItem('user');
            setTimeout(() => {
              window.location.href = `/`;
            }, 1000); // 延迟跳转，让用户看到提示
            return reject(new Error('登录已过期，请重新登录'));
          }
          return reject(new Error(`请求失败: ${response.status}`));
        }
        
        // 强制解析为JSON，确保返回对象而不是字符串
        return response.json().catch(err => {
          console.error('JSON解析失败:', err);
          return reject(new Error('服务器返回格式错误'));
        });
      })
      .then(data => {
        resolve(data); // 这里返回的是解析后的JSON对象
      })
      .catch(err => {
        reject(err);
      });
  });
}
